package com.Iconcat.system.service.impl;

import com.Iconcat.system.controller.CatProjectController;
import com.Iconcat.system.entity.CatProject;
import com.Iconcat.system.entity.CatUser;
import com.Iconcat.system.entity.Investment;
import com.Iconcat.system.service.CatProjectService;
import com.Iconcat.system.service.CatUserService;
import com.Iconcat.system.service.EarningsCalculationService;
import com.Iconcat.system.service.InvestmentService;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class EarningsCalculationServiceImpl implements EarningsCalculationService {

    @Resource
    private CatUserService catUserService;
    @Resource
    private CatProjectService catProjectService;
    @Resource
    private InvestmentService investmentService;

    public BigDecimal calculateDailyEarnings(CatProject project) {
        CatUser user = new CatUser();
        String projectCycle = project.getProjectCycle();
        Boolean projectStatus = project.getProjectStatus();
        // 解析项目周期的数字和单位
        Matcher matcher = Pattern.compile("(\\d+)\\s*([天周月年])").matcher(projectCycle);
        if (matcher.matches()) {
            int duration = Integer.parseInt(matcher.group(1));
            String unit = matcher.group(2);
            System.out.println(duration + unit + "周期");
            // 计算开始时间和结束时间
            LocalDateTime currentTime = LocalDateTime.now();
            LocalDateTime startTime = projectStatus == true ? currentTime : null;

            // 根据单位计算每日收益
            BigDecimal startingAmount = new BigDecimal(project.getStartingAmount());
            BigDecimal returnRate = new BigDecimal(project.getReturnRate());
            // 如果项目状态为false，则不再计算收益
            if (!projectStatus) {

                    LocalDateTime projectEndTime = calculateProjectEndTime(startTime, duration, unit);
                    // 如果当前日期超过项目结束时间，则设置项目状态为已结束
                    if (currentTime.isAfter(projectEndTime)) {
                        project.setProjectStatus(false);
                        // 更新项目状态到数据库，具体方法根据您的实现方式进行调整
                        investmentService.updateProjectStatus(project.getProjectId(), user.getUserId());
                        return BigDecimal.ZERO;
                    }

                return BigDecimal.ZERO;
            }  // 计算每日收益（不考虑周期）
            BigDecimal dailyEarnings = startingAmount.multiply(returnRate);

            switch (unit) {
                case "天":
                    return dailyEarnings;
                case "周":
                    // 假设一周7天，返回每天的收益
                    return dailyEarnings.divide(BigDecimal.valueOf(7), 2, RoundingMode.HALF_UP);
                case "月":
                    // 假设一个月30天，返回每天的收益
                    return dailyEarnings.divide(BigDecimal.valueOf(30), 2, RoundingMode.HALF_UP);
                case "年":
                    // 假设一年365天，返回每天的收益
                    return dailyEarnings.divide(BigDecimal.valueOf(365), 2, RoundingMode.HALF_UP);
                default:
                    // 其他未知单位的处理逻辑
                    break;
            }
        }

        // 如果无法解析项目周期，或者单位不匹配，返回零或其他默认值
        return BigDecimal.ZERO;
    }

    private static final Logger logger = LoggerFactory.getLogger(CatProjectController.class);

    @Scheduled(cron = "0 0 * * * ?")
    public void calculateEarnings() {
        try {
            logger.info("定时任务触发，开始计算收益...");
            // 其他代码
            // 获取所有项目
            List<CatProject> projects = catProjectService.getAllProjects();

            for (CatProject project : projects) {
                if (project != null) {
                    // 计算每个项目的每日收益
                    BigDecimal dailyEarnings = calculateDailyEarnings(project);
                    System.out.println(dailyEarnings + "每日收益");

                    // 获取所有投资了该项目的用户
                    List<Investment> investments = investmentService.getInvestmentsByProjectId(project.getProjectId());


                    for (Investment investment : investments) {
                        System.out.println(investment + "用户");

                        // 更新项目收益到investment表
                        investment.setProjectEarnings(investment.getProjectEarnings().add(dailyEarnings));
                        investmentService.updateById(investment);

                        // 更新用户的总收益
                        updatePendingEarnings(investment.getUserId(), dailyEarnings);
                    }
                    logger.info("定时任务执行完成。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    private void updateTotalEarnings(Integer userId, BigDecimal dailyEarnings) {
//        CatUser user = catUserService.getById(userId);
//        user.setTotalEarnings(user.getTotalEarnings().add(dailyEarnings));
//        catUserService.updateById(user);
//    }
    private void updatePendingEarnings(Integer userId, BigDecimal dailyEarnings) {
        CatUser user = catUserService.getById(userId);
        user.setPendingEarnings(user.getPendingEarnings().add(dailyEarnings));
        catUserService.updateById(user);
    }

    @Scheduled(cron = "0 0 */2 * * ?")// 每天凌晨1点触发，用于累积待收益到总收益
    public void accumulateEarnings() {
        try {
            logger.info("定时任务触发，开始累积待收益到总收益...");

            // 获取所有用户
            List<CatUser> users = catUserService.list();

            for (CatUser user : users) {
                if (user != null) {
                    BigDecimal pendingEarnings = user.getPendingEarnings();
                    if (pendingEarnings.compareTo(BigDecimal.ZERO) > 0) {
                        // 将待收益累积到总收益
                        user.setTotalEarnings(user.getTotalEarnings().add(pendingEarnings));
                        // 清零待收益
                        user.setPendingEarnings(BigDecimal.ZERO);
                        catUserService.updateById(user);
                    }
                }
            }

            logger.info("定时任务执行完成。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private LocalDateTime calculateProjectEndTime(LocalDateTime startTime, int duration, String unit) {
        switch (unit) {
            case "天":
                return startTime.plusDays(duration);
            case "周":
                return startTime.plusWeeks(duration);
            case "月":
                return startTime.plusMonths(duration);
            case "年":
                return startTime.plusYears(duration);
            default:
                // 其他未知单位的处理逻辑
                return startTime;
        }
    }
}
